<template>
    <view class="x-delivery-time">
        <uni-popup ref="popup" type="bottom" :safe-area="safeArea" @change="$emit('update:modelValue', $event.show)">
            <view class="popup" :style="customStyle">
                <view class="title">
                    <text>{{ title }}</text>
                </view>
                <view class="main">
                    <scroll-view class="left" scroll-y="true">
                        <view class="dateList">
                            <view class="date_item" :class="{active: idx == dateIdx}" v-for="(i, idx) in dateList" @click="dateClick(i, idx)">
                                {{ i.text }}
                            </view>
                        </view>
                    </scroll-view>
                    <scroll-view v-if="dateList[dateIdx]" class="right" :scroll-top="timeScrollTop" scroll-y="true">
                        <view class="timeList">
                            <view v-if="dateIdx == 0 && fastestShow" class="time_item" @click="timeClick(fastestText, -1)">
                                <text :style="{color: timeIdx == -1 ? activeColor : ''}">{{ fastestText }}</text>
                                <slot v-if="timeIdx == -1" name="icon"></slot>
                            </view>
                            <view class="time_item" v-for="(i, idx) in timeList" @click="timeClick(i, idx)">
                                <text :style="{color: timeIdx == idx ? activeColor : ''}">{{ i }}</text>
                                <slot v-if="timeIdx == idx" name="icon"></slot>
                            </view>
                        </view>
                    </scroll-view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    export default {
        name: "x-delivery-time",
        props: {
            // 弹窗显示,  vue2 :model-value.sync="show", vue3 v-model="show"
            modelValue: {
                type: Boolean,
                default: false
            },
            // 可选日期, 默认近七天
            dateNum: {
                type: Number,
                default: 7
            },
            // 每日可选开始时间
            limitBeginTime: {
                type: [String, Number],
                default: '0920',
            },
            // 每日可选结束时间
            limitEndTime: {
                type: [String, Number],
                default: '2130',
            },
            // 标题
            title: {
                type: String,
                default: '选择送达时间'
            },
            // 最快时间文本
            fastestText: {
                type: String,
                default: '尽快送达'
            },
            // 是否显示尽快送达
            fastestShow: {
                type: Boolean,
                default: true
            },
            // 选中颜色
            activeColor: {
                type: String,
                default: 'skyblue'
            },
            // 自定义样式
            customStyle: {
                type: Object,
                default: () => ({})
            },
            safeArea: {
                type: Boolean,
                default: true
            },
        },
        emits: ['change', 'update:modelValue'],
        watch: {
            modelValue: {
                handler(val) {
                    if (this.$refs.popup) {
                        if (val) {
                            this.$refs.popup.open()
                        } else {
                            this.$refs.popup.close()
                        }
                    } else {
                        this.$nextTick(() => {
                            // H5 延迟处理 (解决 uni-popup 立即打开会自动关闭问题)
                            // #ifdef H5
                            setTimeout(() => {
                                // #endif
                                if (val) {
                                    this.$refs.popup.open()
                                } else {
                                    this.$refs.popup.close()
                                }
                                // #ifdef H5
                            }, 1000)
                            // #endif
                        })
                    }
                },
                immediate: true
            }
        },
        data() {
            return {
                dateList: [],
                dateIdx: 0,
                timeList: [],
                timeIdx: -1,
                timeScrollTop: 0,
                initTimeList: []
            };
        },
        mounted() {
            this.init()
        },
        methods: {
            init() {
                this.dateList = []
                this.timeList = []
                this.dateIdx = 0
                this.timeIdx = this.fastestShow ? -1 : 0
                const currentDate = new Date()
                const dateMap = ['日', '一', '二', '三', '四', '五', '六']
                for (let i = 0; i < this.dateNum; i++) {

                    let text, year, month, date

                    if (i == 0) {
                        text = '今天'
                    } else {
                        currentDate.setDate(currentDate.getDate() + 1)
                        text = `周${dateMap[currentDate.getDay()]}`
                    }
                    if (i == 1) {
                        text = '明天'
                    }

                    year = currentDate.getFullYear().toString().padStart(2, 0)
                    month = (currentDate.getMonth() + 1).toString().padStart(2, 0)
                    date = currentDate.getDate().toString().padStart(2, 0)

                    text += ` ${month}月${date}日`
                    date = `${year}/${month}/${date}`

                    this.dateList.push({
                        text,
                        date
                    })
                }

                for (let i = 0; i < 24; i++) {
                    this.initTimeList.push(`${i.toString().padStart(2,0)}:00-${i.toString().padStart(2,0)}:30`)
                    this.initTimeList.push(`${i.toString().padStart(2,0)}:30-${(i + 1).toString().padStart(2,0)}:00`)
                }

                this.timeListFilter()
                this.onChange()
            },
            dateClick(i, idx) {
                this.dateIdx = idx
                this.timeScrollTop--
                if (idx || !this.fastestShow) {
                    this.timeIdx = 0
                } else {
                    this.timeIdx = -1
                }
                this.timeListFilter()
                this.onChange()
            },
            timeClick(i, idx) {
                this.timeIdx = idx
                this.onChange()
            },
            timeListFilter() {
                let limitBeginTime, limitEndTime
                limitBeginTime = parseInt(this.limitBeginTime)
                limitEndTime = parseInt(this.limitEndTime)
                this.timeList = this.initTimeList.filter(i => {
                    let [begin, end] = i.split('-')
                    if (this.dateIdx) {
                        return parseInt(end.replace(':', '')) >= limitBeginTime && parseInt(end.replace(':', '')) <= limitEndTime
                    } else {
                        return (parseInt(begin.replace(':', '')) >= limitBeginTime && parseInt(end.replace(':', '')) <= limitEndTime) && new Date().getTime() < +new Date(this.dateList[this
                            .dateIdx].date + ' ' + end)
                    }
                })
            },
            onChange() {
                const activeDate = this.dateList[this.dateIdx]
                const activeTime = this.timeList[this.timeIdx]
                if (this.timeIdx == -1) {
                    this.$emit('change', {
                        date: activeDate.date,
                        dateBegin: activeDate.date,
                        dateEnd: activeDate.date,
                        time: activeTime,
                        dateTime: activeDate.date,
                    })
                } else {
                    let [begin, end] = activeTime.split('-')
                    begin = activeDate.date + ' ' + begin
                    end = activeDate.date + ' ' + end

                    this.$emit('change', {
                        date: activeDate.date,
                        dateBegin: begin,
                        dateEnd: end,
                        time: activeTime,
                        dateTime: activeDate.date + ' ' + activeTime,
                    })
                }
            }
        }
    }
</script>

<style lang="scss">
    .popup {
        width: 750rpx;
        height: 750rpx;
        background-color: #fff;
        border-radius: 20rpx 20rpx 0 0;

        .title {
            height: 100rpx;
            font-weight: bold;
            font-size: 32rpx;
            color: #333333;
            text-align: center;
            line-height: 100rpx;
        }

        .main {
            display: flex;
        }

        .left,
        .right {
            height: 650rpx;
        }

        .left {
            width: 216rpx;
            background-color: #f7f7f7;
            text-align: center;

            .date_item {
                height: 104rpx;
                line-height: 104rpx;
                text-align: center;
                font-weight: bold;
                font-size: 28rpx;
                color: #333333;
            }

            .active {
                background-color: #fff;
            }
        }

        .right {
            width: 534rpx;

            .timeList {
                padding-left: 32rpx;
            }

            .time_item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                width: 502rpx;
                height: 104rpx;
                padding-right: 32rpx;
                border-bottom: 1rpx solid #E5E5E5;

                text {
                    font-weight: bold;
                    font-size: 28rpx;
                    color: #333333;
                }

                &:last-child {
                    border: 0;
                }
            }
        }
    }
</style>